package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import static com.zzyl.common.constant.CacheConstants.DEVICE_LIST_KEY;

/**
 * 设备Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-05
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient  iotDAClient;

    @Autowired
    private RedisTemplate<String , String> redisTemplate;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     * 
     * @param deviceDto 设备
     * @return 结果
     */
    @Transactional
    @Override
    public void updateDevice(DeviceDto deviceDto)
    {
        //1. 判断设备名称是否重复
        Long count = lambdaQuery()
                .eq(Device::getDeviceName, deviceDto.getDeviceName())
                .ne(Device::getId, deviceDto.getId())
                .count();
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }

        //2. 判断同一位置是否绑定了相同的产品
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setLocationType(-1);
        }
        count = lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .ne(Device::getId, deviceDto.getId())
                .count();
        if (count > 0) {
            throw new BaseException("同一位置绑定了相同的产品");
        }

        //3. 修改IOT平台设备数据
        //3.1 完善向平台更新的数据及id
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());
        UpdateDevice requestBody = new UpdateDevice();
        requestBody.withDeviceName(deviceDto.getDeviceName());
        request.withBody(requestBody);
        try {
            iotDAClient.updateDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口调用失败，请联系管理员处理");
        }

        //4. 修改本地数据
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        try {
            updateById(device);
        } catch (Exception e) {
            throw new BaseException("相同位置不能绑定同一设备");
        }
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     * 
     * @param iotId 设备Id
     * @return 结果
     */
    @Transactional
    @Override
    public void deleteDeviceById(String iotId)
    {
        //1. 删除数据库设备数据
        int resultCode = deviceMapper.delete(new QueryWrapper<Device>().eq("iot_id", iotId));

        //2. 删除IOT平台设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response;
        try {
            response = iotDAClient.deleteDevice(request);
        } catch (Exception e) {
            log.error("删除设备失败", e);
            throw new BaseException("删除设备失败");
        }
        if (resultCode != 1&& response.getHttpStatusCode() != 204) {
           throw new BaseException("删除设备失败");
        }
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductListy() {
        //1. 从iot平台获取产品列表
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = iotDAClient.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("同步产品列表失败");
        }

        //2. 将产品保存到redis数据库中
        List<ProductSummary> products = response.getProducts();
        if (ObjectUtil.isEmpty(products)) {
            log.warn("产品列表为空");
            return;
        }
        redisTemplate.opsForValue().set(DEVICE_LIST_KEY, JSONUtil.toJsonStr(products));
    }

    /**
     * 查询全部产品列表
     * @return
     */
    @Override
    public List<ProductVo> allProductList() {
        String productList = redisTemplate.opsForValue().get(DEVICE_LIST_KEY);
        List<ProductVo> products = JSONUtil.toList(productList, ProductVo.class);
        return products;
    }

    /**
     * 注册设备
     * @param deviceDto
     */
    @Transactional
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1. 判断设备名称是否重复
        Long count = lambdaQuery()
                .eq(Device::getDeviceName, deviceDto.getDeviceName())
                .count();
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }

        //2. 判断设备标识是否重复
        count = lambdaQuery()
                .eq(Device::getNodeId, deviceDto.getNodeId())
                .count();
        if (count > 0) {
            throw new BaseException("设备标识码重复");
        }

        // 如果是随身设备，将物理物理位置类型设置为-1
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }

        //3. 判断同一位置是否绑定了同类型的产品
        count = lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .count();
        if (count > 0) {
            throw new BaseException("同一位置已绑定同类型产品");
        }

        //4. 注册设备到华为云IOT平台
        // 随机生成密码
        String secret = UUID.randomUUID().toString().replaceAll("-", "");

        // 生成注册设备请求
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice
                .withDeviceName(deviceDto.getDeviceName())
                .withProductId(deviceDto.getProductKey())
                .withNodeId(deviceDto.getNodeId())
                .withAuthInfo(new AuthInfo()
                    .withSecret(secret));
        addDeviceRequest.withBody(addDevice);
        AddDeviceResponse response ;
        try {
            response = iotDAClient.addDevice(addDeviceRequest);
        } catch (Exception e) {
            log.error("设备注册失败", e);
            throw new BaseException("设备注册失败");
        }

        //5. 保存设备数据到数据库中
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setSecret(secret);
        device.setIotId(response.getDeviceId());
        save(device);

    }

    /**
     * 查询设备详情
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo qureyDevicDetail(String iotId) {
        //1. 根据设备id查询数据库设备数据
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }

        //2. 查询IOT平台设备数据
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = iotDAClient.showDevice(request);
        } catch (Exception e) {
            log.info("查询设备详情失败");
            throw new BaseException("查询设备详情失败");
        }

        //3. 进行数据封装并返回
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        // 设置设备状态
        deviceDetailVo.setDeviceStatus(response.getStatus());
        // 设置激活时间
        String activeTimeStr = response.getActiveTime();
        // 将activeTimeStr设置为LocalDateTime,并将时间设置为上海时间
        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }

        return deviceDetailVo;
    }

    /**
     * 查询设备上报数据
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = iotDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询设备上报数据失败");
        }

        // 获取上报数据
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            // 上报数据为空，则返回空数据
            return AjaxResult.success(CollUtil.newArrayList());
        }
        // 如果查询上报数据不为空，则解析上报数据
        JSONObject entries = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        List<Map<String, Object>> list = new ArrayList<>();
        // 将上报时间转换为LocalDateTime
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        // 日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        // 将获取上报数据存储至集合中，并返回
        entries.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return AjaxResult.success(list);
    }

    /**
     * 查询产品服务详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("产品ID不能为空");
        }

        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse showProductResponse;
        // 调用第三方IOT平台
        try {
            showProductResponse = iotDAClient.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("物联网平台查询失败，请稍后再试");
        }

        // 判断查询数据是否为空
        List<ServiceCapability> serviceCapabilities = showProductResponse.getServiceCapabilities();
        if (CollUtil.isEmpty(serviceCapabilities)) {
            // 没有服务数据，返回一个空集合
            return AjaxResult.success(Collections.emptyList());
        }
        return AjaxResult.success(serviceCapabilities);
    }
}
